package com.zjtx.blog.service;

import com.zjtx.blog.utils.SecurityConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Map;
import java.util.Set;

@Service
public class SecurityAnalyzerService {
    
    private static final Logger logger = LoggerFactory.getLogger(SecurityAnalyzerService.class);
    
    @Autowired
    private RedisSecurityService redisSecurityService;
    
    @Autowired
    private StringRedisTemplate redisTemplate;
    
    /**
     * 分析请求参数中的恶意内容
     */
    public boolean containsMaliciousContent(HttpServletRequest request) {
        // 检查查询参数
        Map<String, String[]> parameterMap = request.getParameterMap();
        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
            for (String value : entry.getValue()) {
                if (isMaliciousContent(value)) {
                    return true;
                }
            }
        }
        return false;
    }
    
    /**
     * 检查内容是否包含恶意模式
     */
    private boolean isMaliciousContent(String content) {
        if (content == null || content.isEmpty()) {
            return false;
        }
        
        String lowerContent = content.toLowerCase();
        return SecurityConstants.ATTACK_PATTERNS.stream()
                .anyMatch(pattern -> lowerContent.contains(pattern.toLowerCase()));
    }
    
    /**
     * 获取请求体内容
     */
    private String getRequestBody(HttpServletRequest request) throws IOException {
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = request.getReader();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        return sb.toString();
    }
    
    /**
     * 分析高频访问IP并自动加入黑名单
     */
    @Scheduled(fixedRate = 60000)
    public void analyzeAndBlockHighFrequencyIps() {
        Set<String> keys = redisTemplate.keys("security:ip:request:count:*");
        if (keys == null || keys.isEmpty()) {
            return;
        }
        
        for (String key : keys) {
            try {
                String ip = key.substring("security:ip:request:count:".length());
                String countStr = redisTemplate.opsForValue().get(key);
                
                if (countStr != null) {
                    long count = Long.parseLong(countStr);
                    if (count > 200) {
                        redisSecurityService.blacklistIp(ip, "High frequency access: " + count + " requests/min");
                        logger.warn("Auto-blacklisted IP {} for high frequency access ({} requests)", ip, count);
                    }
                }
            } catch (Exception e) {
                logger.warn("Error analyzing key: {}", key, e);
            }
        }
    }
    
    /**
     * 定期清理过期的安全记录
     */
    @Scheduled(fixedRate = 3600000)
    public void cleanupSecurityRecords() {
        logger.info("Performing security cache cleanup");
    }
}
